package com.hmall.item.listener;

import com.hmall.api.client.TradeClient;
import com.hmall.api.dto.OrderDetailDTO;
import com.hmall.item.constants.MQConstants;
import com.hmall.item.service.IItemService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@RequiredArgsConstructor
public class PayStatusListener {

    private final IItemService itemService;
    private final TradeClient tradeClient;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MQConstants.RECOVER_ORDER_QUEUE_NAME, durable = "true"),
            exchange = @Exchange(name = MQConstants.RECOVER_EXCHANGE_NAME, type = ExchangeTypes.DIRECT),
            key = MQConstants.RECOVER_ORDER_KEY
    ))
    public void updateSuccess(Long orderId){
        // 根据订单ID查询订单详情
        List<OrderDetailDTO> orderDetails = tradeClient.queryOrderDetailsById(orderId);
        // 将订单中商品的数量加回到商品库存中
        itemService.restoreStock(orderDetails);
    }

}